import pandas as pd
from gate_api import SpotApi, FuturesApi, Configuration, ApiClient
import time
from datetime import datetime

class GateFundingRate:
    def __init__(self, api_key: str, api_secret: str):
        # 初始化API客户端
        configuration = Configuration(
            key=api_key,
            secret=api_secret,
            host="https://api.gateio.ws/api/v4"
        )
        self.client = ApiClient(configuration)
        self.futures_api = FuturesApi(self.client)
        
    def get_funding_rates(self):
        try:
            # 获取所有永续合约
            contracts = self.futures_api.list_futures_contracts('usdt')
            
            # 准备数据列表
            funding_data = []
            
            for contract in contracts:
                if contract.name.endswith('USDT'):  # 只处理USDT合约
                    try:
                        # 获取合约信息
                        contract_detail = self.futures_api.get_futures_contract(settle='usdt', contract=contract.name)
                        
                        # 获取实时资金费率 - 使用正确的API方法
                        funding_info = self.futures_api.list_futures_tickers(settle='usdt', contract=contract.name)
                        
                        if funding_info and len(funding_info) > 0:
                            ticker = funding_info[0]
                            
                            # 构建数据
                            data = {
                                'symbol': contract.name,  # 币对名称
                                'funding_rate': float(ticker.funding_rate) * 100,  # 当前资金费率(%)
                                'next_funding_time': '',  # 下次结算时间
                                'interval': f"{contract_detail.funding_interval}h"  # 结算周期
                            }
                            print(data)
                            funding_data.append(data)
                            
                        time.sleep(0.1)  # 添加延迟避免请求过快
                        
                    except Exception as e:
                        print(f"获取{contract.name}资金费率失败: {str(e)}")
                        continue
            
            # 转换为DataFrame
            df = pd.DataFrame(funding_data)
            
            # 按资金费率排序
            df = df.sort_values(by='funding_rate', ascending=False)
            
            # 添加年化收益率列
            df['annual_rate'] = df.apply(lambda row: self._calculate_annual_rate(row['funding_rate'], row['interval']), axis=1)
            
            # 保存为CSV
            current_time = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f'gate_funding_rate_{current_time}.csv'
            df.to_csv(filename, index=False)
            
            print(f"资金费率数据已保存到: {filename}")
            return df
            
        except Exception as e:
            print(f"获取资金费率失败: {str(e)}")
            return None
            
    def _calculate_annual_rate(self, funding_rate, interval):
        """计算年化收益率"""
        hours = int(interval.replace('h', ''))
        times_per_year = (365 * 24) / hours
        return funding_rate * times_per_year

def main():
    # 使用您的API密钥
    api_key = "3e8bf1c102bedfdea327212db1b466be"
    api_secret = "d8d6024fa11a053f71d7dd20c1ce0713335d0b4e88e80ba11a844c00684e1d84"
    
    # 创建GateFundingRate实例
    gate_funding = GateFundingRate(api_key, api_secret)
    
    # 获取并保存资金费率
    funding_rates = gate_funding.get_funding_rates()
    
    if funding_rates is not None:
        print("\n资金费率前10名:")
        print(funding_rates[['symbol', 'funding_rate', 'interval', 'annual_rate']].head(10))

if __name__ == "__main__":
    main()
